package com.ruoyi.game.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.game.controller.dto.GamePlayerLoginReq;
import com.ruoyi.game.controller.dto.GamePlayerRegisterReq;
import com.ruoyi.game.controller.dto.RechargeReq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.game.domain.GamePlayer;
import com.ruoyi.game.service.IGamePlayerService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 玩家信息Controller
 * 
 * @author ruoyi
 * @date 2025-04-18
 */
@Slf4j
@Api(tags = "玩家管理接口")
@RestController
@RequestMapping("/game/player")
public class GamePlayerController extends BaseController
{
    @Autowired
    private IGamePlayerService gamePlayerService;
    @Autowired
    private TokenService tokenService;

    @ApiOperation("玩家注册")
    @PostMapping("/register")
    public AjaxResult register(@RequestBody GamePlayerRegisterReq req) {
        if (StringUtils.isEmpty(req.getMobile()) || StringUtils.isEmpty(req.getPassword())) {
            return AjaxResult.error("手机号或密码不能为空");
        }

        GamePlayer exists = gamePlayerService.selectByUsername(req.getMobile());
        if (exists != null) {
            return AjaxResult.error("手机号已注册");
        }

        GamePlayer player = new GamePlayer();
        player.setUsername(req.getMobile());
        player.setNickname(req.getNickname());
        player.setPassword(SecurityUtils.encryptPassword(req.getPassword()));
        player.setRoomCard(10l); // 初始送房卡，可调整

        gamePlayerService.insertGamePlayer(player);

        // ✅ 自动登录
        SysUser fakeUser = new SysUser();
        fakeUser.setUserId(player.getId());
        fakeUser.setUserName(player.getUsername());

        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(player.getId());
        loginUser.setUser(fakeUser);

        String token = tokenService.createToken(loginUser);

        return AjaxResult.success("注册成功")
                .put("token", token)
                .put("player", buildPlayerInfo(player));
    }

    private Map<String, Object> buildPlayerInfo(GamePlayer player) {
        Map<String, Object> info = new HashMap<>();
        info.put("id", player.getId());
        info.put("nickname", player.getNickname());
        info.put("avatar", player.getAvatar());
        info.put("sex", player.getSex());
        info.put("roomCard", player.getRoomCard());
        return info;
    }

    @ApiOperation("玩家登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody GamePlayerLoginReq req) {
        GamePlayer dbUser = gamePlayerService.selectByUsername(req.getMobile());
        if (dbUser == null) {
            return AjaxResult.error("用户不存在");
        }

        if (!SecurityUtils.matchesPassword(req.getPassword(), dbUser.getPassword())) {
            return AjaxResult.error("密码错误");
        }

        SysUser fakeUser = new SysUser();
        fakeUser.setUserId(dbUser.getId());
        fakeUser.setUserName(dbUser.getUsername());

        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(dbUser.getId());
        loginUser.setUser(fakeUser);

        String token = tokenService.createToken(loginUser);

        return AjaxResult.success("登录成功")
                .put("token", token)
                .put("player", buildPlayerInfo(dbUser));
    }

    @ApiOperation("充值房卡")
    @PostMapping("/recharge")
    public AjaxResult recharge(@RequestBody @ApiParam("充值信息") RechargeReq req, HttpServletRequest request) {
        // 1. 从 token 里解析 playerId
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser == null) {
            return AjaxResult.error("未登录或登录已失效");
        }
        Long playerId = loginUser.getUserId(); // 这里拿到玩家ID
        log.info("[充值房卡] 当前登录玩家ID={}", playerId);

        // 2. 处理充值请求
        Long amount = req.getAmount();
        String remark = req.getRemark() != null ? req.getRemark() : "后台加卡";

        // 进行充值操作
        Long updated = gamePlayerService.recharge(playerId, amount, remark);
        Long roomCard = gamePlayerService.getRoomcardByPlayerId(playerId);

        log.info("[充值房卡] 玩家ID={}，充值金额={}，当前余额={}", playerId, amount, roomCard);
        return AjaxResult.success("充值成功").put("roomCard", roomCard);
    }


    /**
     * 查询玩家信息列表
     */
    @ApiOperation("查询玩家信息列表")
    // @PreAuthorize("@ss.hasPermi('game:player:list')")
    @GetMapping("/list")
    public TableDataInfo list(GamePlayer gamePlayer)
    {
        startPage();
        List<GamePlayer> list = gamePlayerService.selectGamePlayerList(gamePlayer);
        return getDataTable(list);
    }

    @ApiOperation("获取玩家房卡余额")
    @ApiImplicitParam(name = "playerId", value = "玩家ID", required = true, dataTypeClass = Long.class)
    @GetMapping("/roomCard")
    public AjaxResult getRoomCard(@RequestParam("playerId") Long playerId) {
        GamePlayer player = gamePlayerService.selectGamePlayerById(playerId);
        if (player == null) {
            return error("玩家不存在");
        }
        return success(player.getRoomCard());
    }

    /**
     * 导出玩家信息列表
     */
    @ApiOperation("导出玩家信息列表")
    // @PreAuthorize("@ss.hasPermi('game:player:export')")
    @Log(title = "玩家信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GamePlayer gamePlayer)
    {
        List<GamePlayer> list = gamePlayerService.selectGamePlayerList(gamePlayer);
        ExcelUtil<GamePlayer> util = new ExcelUtil<GamePlayer>(GamePlayer.class);
        util.exportExcel(response, list, "玩家信息数据");
    }

    /**
     * 获取玩家信息详细信息
     */
    @ApiOperation("获取玩家详情")
    // @PreAuthorize("@ss.hasPermi('game:player:query')")
    @ApiImplicitParam(name = "id", value = "玩家ID", required = true, dataTypeClass = Long.class)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(gamePlayerService.selectGamePlayerById(id));
    }

    /**
     * 新增玩家信息
     */
//    @ApiOperation("新增玩家信息")
//    // @PreAuthorize("@ss.hasPermi('game:player:add')")
//    @Log(title = "玩家信息", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody GamePlayer gamePlayer)
//    {
//        return toAjax(gamePlayerService.insertGamePlayer(gamePlayer));
//    }

    /**
     * 修改玩家信息
     */
    @ApiOperation("修改玩家信息")
    // @PreAuthorize("@ss.hasPermi('game:player:edit')")
    @Log(title = "玩家信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GamePlayer gamePlayer)
    {
        return toAjax(gamePlayerService.updateGamePlayer(gamePlayer));
    }

    /**
     * 删除玩家信息
     */
    @ApiOperation("删除玩家信息")
    // @PreAuthorize("@ss.hasPermi('game:player:remove')")
    @Log(title = "玩家信息", businessType = BusinessType.DELETE)
    @ApiImplicitParam(name = "ids", value = "玩家ID数组", required = true, dataTypeClass = Long.class)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(gamePlayerService.deleteGamePlayerByIds(ids));
    }
}
